#!/bin/sh
# Rise Vision Player installation script

set -e

DISPLAY_ID="#DISPLAY_ID#" 

VERSION="1.2.0017-test" # "1.2.0017"

RVPLAYER="rvplayer"
CHROMIUM="chrome"
PROXY="polipo"

CHROME_LINUX="chrome-linux"
# FLASH_LINUX="libgcflashplayer"
PROXY_LINUX="polipo"

CORE_URL="https://rvacore-test.appspot.com" # "https://rvaserver2.appspot.com"
SHOW_URL="http://viewer-test.appspot.com" # "http://rvashow.appspot.com"

TYPE_CHROMIUM="chromium"
TYPE_FLASH="flash"
TYPE_INSTALLER="installer"
TYPE_PROXY="polipo"

VIEWER_URL="$SHOW_URL/Viewer.html?type=display&id=$DISPLAY_ID"

PREFERENCES="{\"countryid_at_install\":0,\"default_search_provider\":{\"enabled\":false},\"geolocation\":{\"default_content_setting\":1},\"profile\":{\"content_settings\":{\"pref_version\":1},\"exited_cleanly\":true}}"

CONFIG_PATH=".config/$RVPLAYER"
CACHE_PATH=".cache/$RVPLAYER"
PREFERENCES_PATH=".config/$RVPLAYER/Default"
FIRST_RUN_FILE="First Run"
PREFERENCES_FILE="Preferences"
RDNII_FILE="RiseDisplayNetworkII.ini"

TEMP_PATH="$HOME/$RVPLAYER/temp"
INSTALL_PATH="$HOME/$RVPLAYER"
STARTUP_SCRIPT_FILE="$HOME/$RVPLAYER/$RVPLAYER"

PROXY_PATH="$HOME/$RVPLAYER/$PROXY"
PROXY_CONFIG_FILE="$PROXY_PATH/config"
PROXY_PID_FILE="$PROXY_PATH/$PROXY.pid"
PROXY_LOG_FILE="$PROXY_PATH/$PROXY.log"
PROXY_CACHE_PATH="$PROXY_PATH/cache"
PROXY_UNCACHABLE_FILE="$PROXY_PATH/uncachable"
PROXY_PORT="8123"

AUTOSTART_PATH="$HOME/.config/autostart"
AUTOSTART_FILE="$RVPLAYER.desktop"

PARAM_RESTART="Restart"
PARAM_PURGE="Purge"
PARAM_INSTALLER_UPGRADE="InstallerUpgrade"
PARAM_CHROMIUM_VERSION="ChromiumVersion"
PARAM_CHROMIUM_URL="ChromiumURL"
PARAM_FLASH_VERSION="FlashVersion"
PARAM_FLASH_URL="FlashURL"
PARAM_PROXY_VERSION="CacheVersion"
PARAM_PROXY_URL="CacheURL"

VALUE_NO="0"
VALUE_YES="1"

VALUE_RESTART=$VALUE_NO
VALUE_PURGE=$VALUE_NO
VALUE_INSTALLER_UPGRADE=$VALUE_NO
VALUE_CHROMIUM_VERSION=""
VALUE_CHROMIUM_URL=""
VALUE_FLASH_VERSION=""
VALUE_FLASH_URL=""
VALUE_PROXY_VERSION=""
VALUE_PROXY_URL=""


rvp_exit_with_error() {

	rm -rf $TEMP_PATH

	echo $1
	echo "Rise Vision Player is NOT installed."
	exit 0
}

rvp_install_script() {

	mkdir -p $INSTALL_PATH

	abspath=$(cd ${0%/*} && echo $PWD/${0##*/})

	if [ $abspath != $STARTUP_SCRIPT_FILE ]; then

		cp $abspath $STARTUP_SCRIPT_FILE
		chmod 755 $STARTUP_SCRIPT_FILE
		echo "Startup script updated."
	fi

}

rvp_get_update() {

	curr_date=$(date +%d%m%Y%H%M)
	chromium_ver=`cat $INSTALL_PATH/$TYPE_CHROMIUM"_version" 2>&1` || chromium_ver=""
	flash_ver=`cat $INSTALL_PATH/$TYPE_FLASH"_version" 2>&1` || flash_ver=""
	proxy_ver=`cat $INSTALL_PATH/$TYPE_PROXY"_version" 2>&1` || proxy_ver=""

	update_url="$CORE_URL/player/update?os=lnx&id=$DISPLAY_ID&ts=$curr_date&iv=$VERSION&cv=$chromium_ver&fv=$flash_ver&hv=$proxy_ver"

	echo "Checking for updates..."

	set +e

	update_content=`wget -O - "$update_url"` || update_content="" # rvp_exit_with_error "Update check failed"

	set -e

	upgrade_needed=$VALUE_NO	

	for line in $update_content ; do

		echo $line

	 	p_name="$(echo "$line" | cut -d = -f 1)"
		p_value="$(echo "$line" | cut -d = -f 2)"
		   	
		case $p_name in

			$PARAM_RESTART ) VALUE_RESTART=$p_value ;; 
			$PARAM_PURGE ) VALUE_PURGE=$p_value ;; 
			$PARAM_INSTALLER_UPGRADE ) VALUE_INSTALLER_UPGRADE=$p_value ;;
			$PARAM_CHROMIUM_VERSION ) VALUE_CHROMIUM_VERSION=$p_value ;;
			$PARAM_CHROMIUM_URL ) VALUE_CHROMIUM_URL=$p_value ;;
			$PARAM_FLASH_VERSION ) VALUE_FLASH_VERSION=$p_value ;;
			$PARAM_FLASH_URL ) VALUE_FLASH_URL=$p_value ;;
			$PARAM_PROXY_VERSION ) VALUE_PROXY_VERSION=$p_value ;;
			$PARAM_PROXY_URL ) VALUE_PROXY_URL=$p_value ;;

			
		esac
	   
	done
}

rvp_kill_chromium() {

	killall "$CHROMIUM" || echo "no Chromiums to kill"
	sleep 3

	if ps ax | grep -v grep | grep $CHROMIUM > /dev/null
	then
		sleep 10

		if ps ax | grep -v grep | grep $CHROMIUM > /dev/null
		then
			killall "$CHROMIUM" || echo "no Chromiums to kill"
			sleep 3
		fi	
	fi
}

rvp_kill_proxy() {

	[ -f "$PROXY_PID_FILE" ] && kill -USR1 $(cat "$PROXY_PID_FILE")
	sleep 1
}

rvp_reset_chromium() {

	echo "Restarting Chromium and clearing its cache..."

	rvp_kill_chromium
	rm -rf $HOME/$CACHE_PATH
	rm -rf $HOME/$CONFIG_PATH
}

rvp_reset_proxy() {

	echo "Restarting Proxy and purging expired data from its cache..."

	rvp_kill_proxy
	$PROXY_PATH/$PROXY -x -c $PROXY_CONFIG_FILE pidFile=$PROXY_PID_FILE logFile=$PROXY_LOG_FILE proxyPort=$PROXY_PORT diskCacheRoot=$PROXY_CACHE_PATH 
	[ -f "$PROXY_PID_FILE" ] && kill -USR2 $(cat "$PROXY_PID_FILE")
	
}

rvp_download_and_run_installer() {

	
	abspath=$(cd ${0%/*} && echo $PWD/${0##*/})
	
	echo $abspath

	installer_url="$CORE_URL/player/download?os=lnx&displayId=$DISPLAY_ID"

	# setting wget options
	:> wgetrc
	echo "noclobber = off" >> wgetrc
	echo "dir_prefix = ." >> wgetrc
	echo "dirstruct = off" >> wgetrc
	echo "verbose = on" >> wgetrc
	echo "progress = dot:default" >> wgetrc
	echo "output-document = $abspath" >> wgetrc
	# downloading zip
	echo "Downloading..."
	WGETRC=wgetrc wget $installer_url || rvp_exit_with_error "Installer download failed"
	rm -f wgetrc
	echo "Download complete."
	
	chmod 755 $abspath
	$abspath

	# exit this version and let new version take over
	exit 0

}

rvp_download_and_unpack() {

	mkdir -p $3
	cd $3
	
	# setting wget options
	:> wgetrc
	echo "noclobber = off" >> wgetrc
	echo "dir_prefix = ." >> wgetrc
	echo "dirstruct = off" >> wgetrc
	echo "verbose = on" >> wgetrc
	echo "progress = dot:default" >> wgetrc
	echo "output-document = $2.zip" >> wgetrc 

	# downloading zip
	echo "Downloading..."
	rm -f "$2.zip"
	WGETRC=wgetrc wget $1 || rvp_exit_with_error "Download failed"
	rm -f wgetrc
	echo "Download complete."

	rm -rf $2*/

	# unzipping
	unzip -b "$2.zip" || rvp_exit_with_error "Cannot unzip $2.zip"
	
	rm -f "$2.zip"
}

rvp_install_updates() {

	rvp_kill_chromium
	rvp_kill_proxy
	
	cd $TEMP_PATH
	find * -print | cpio -pvdmu $INSTALL_PATH/
	
	chmod -R g+r,a+r,a+X $INSTALL_PATH/*
	# chmod a+x $INSTALL_PATH/$CHROME_LINUX/$FLASH_LINUX*
	
	cd $INSTALL_PATH
	rm -rf $TEMP_PATH*
		
} 

rvp_add_player_to_autostart() {

	mkdir -p $AUTOSTART_PATH
	:> $AUTOSTART_PATH/$AUTOSTART_FILE
	echo "[Desktop Entry]" >> $AUTOSTART_PATH/$AUTOSTART_FILE
	echo "Encoding=UTF-8" >> $AUTOSTART_PATH/$AUTOSTART_FILE
	echo "Name=Rise Vision Player" >> $AUTOSTART_PATH/$AUTOSTART_FILE
	echo "Comment=" >> $AUTOSTART_PATH/$AUTOSTART_FILE
	echo "Icon=" >> $AUTOSTART_PATH/$AUTOSTART_FILE
	echo "Exec=$STARTUP_SCRIPT_FILE" >> $AUTOSTART_PATH/$AUTOSTART_FILE
	echo "Terminal=false" >> $AUTOSTART_PATH/$AUTOSTART_FILE
	echo "Type=Application" >> $AUTOSTART_PATH/$AUTOSTART_FILE
	echo "Categories=" >> $AUTOSTART_PATH/$AUTOSTART_FILE
	echo "NotShowIn=KDE;" >> $AUTOSTART_PATH/$AUTOSTART_FILE
	echo "X-GNOME-Autostart-Delay=10" >> $AUTOSTART_PATH/$AUTOSTART_FILE
	echo "X-Ubuntu-Gettext-Domain=$RVPLAYER" >> $AUTOSTART_PATH/$AUTOSTART_FILE

	chmod 755 $AUTOSTART_PATH/$AUTOSTART_FILE

}

rvp_install_to_crontab() {

	# run every 10 min
	echo "*/10 * * * * $STARTUP_SCRIPT_FILE > $HOME/rvplayer.log 2>&1" | crontab -

}

rvp_save_display_id() {
	if [ ! -e "$INSTALL_PATH/$RDNII_FILE" ]
	then		
		echo "[RDNII]
displayid=$DISPLAY_ID
" > $INSTALL_PATH/$RDNII_FILE
	fi
}

rvp_start_player() {

	if [ -f "$PROXY_PID_FILE" ] && [ -f /proc/$(cat "$PROXY_PID_FILE")/exe ]
	then	
		echo "Cache is already running"
	else
			
		# delete pid file
		rm -f $PROXY_PID_FILE
		
		# wipe javascript from the cache if any is there
		find $PROXY_CACHE_PATH -type f -print0 | xargs -0 egrep -Z -l '(javascript)' | xargs -0 rm 2>/dev/null || echo "No Javascript in cache"

		echo "Starting Cache on port $PROXY_PORT..."

		$PROXY_PATH/$PROXY -c $PROXY_CONFIG_FILE pidFile=$PROXY_PID_FILE logFile=$PROXY_LOG_FILE proxyPort=$PROXY_PORT uncachableFile=$PROXY_UNCACHABLE_FILE diskCacheRoot=$PROXY_CACHE_PATH &
	fi

	if ps ax | grep -v grep | grep $CHROMIUM > /dev/null
	then
		echo "Rise Player is already running"
		exit 0
	fi

	cd
	mkdir -p $HOME/$CONFIG_PATH
	mkdir -p $HOME/$PREFERENCES_PATH
	:>"$HOME/$CONFIG_PATH/$FIRST_RUN_FILE"
	:>$HOME/$PREFERENCES_PATH/$PREFERENCES_FILE
	echo "$PREFERENCES" >> $HOME/$PREFERENCES_PATH/$PREFERENCES_FILE

	echo "Starting Rise Player..."
	export DISPLAY=:0
	$INSTALL_PATH/$CHROME_LINUX/$CHROMIUM --kiosk --no-default-browser-check --noerrdialogs --no-message-box --disable-desktop-notifications --allow-running-insecure-content --disk-cache-dir=$HOME/$CACHE_PATH --user-data-dir=$HOME/$CONFIG_PATH --proxy-server=127.0.0.1:$PROXY_PORT "$VIEWER_URL"

}

echo "Rise Vision Player Installer ver.$VERSION"

rvp_get_update

# check for reset first

if [ $VALUE_RESTART = $VALUE_YES ] 
then 
	rvp_reset_chromium  
fi

# check for purge

if [ $VALUE_RESTART = $VALUE_YES ] || [ $VALUE_PURGE = $VALUE_YES ] 
then 
	rvp_reset_proxy  
fi

# check for installer upgrade

if [ $VALUE_INSTALLER_UPGRADE = $VALUE_YES ]
then 
	rvp_download_and_run_installer
else
	echo "Installer is up to date."
fi

rvp_install_script

rvp_save_display_id

rm -rf $TEMP_PATH/$CHROME_LINUX

upgrade_needed=$VALUE_NO

# check for Chromium upgrade

if [ -n "$VALUE_CHROMIUM_VERSION" ] && [ -n "$VALUE_CHROMIUM_URL" ]
then

	rvp_download_and_unpack $VALUE_CHROMIUM_URL $CHROME_LINUX $TEMP_PATH
	echo $VALUE_CHROMIUM_VERSION > $INSTALL_PATH/$TYPE_CHROMIUM"_version"
	upgrade_needed=$VALUE_YES
	rvp_reset_chromium  
else

	echo "Chromium is up to date."
fi

# check for Proxy upgrade

if [ -n "$VALUE_PROXY_VERSION" ] && [ -n "$VALUE_PROXY_URL" ]
then

	rvp_download_and_unpack $VALUE_PROXY_URL $PROXY_LINUX $TEMP_PATH/$PROXY_LINUX
	echo $VALUE_PROXY_VERSION > $INSTALL_PATH/$TYPE_PROXY"_version"
	upgrade_needed=$VALUE_YES
else

	echo "Cache is up to date."
fi

# install upgrades if necessary

if [ $upgrade_needed = $VALUE_YES ] && ([ -d $TEMP_PATH/$CHROME_LINUX ] || [ -d $TEMP_PATH/$PROXY_LINUX ])
then 
	
	echo "Installing updates..."

	rvp_install_updates

	echo "Updates installed."
fi

rvp_add_player_to_autostart

rvp_install_to_crontab

rvp_start_player